import React, { useState, useEffect } from 'react';
import { useModel, history } from 'umi'
import styles from '../css/cart.less'
import { CheckCircleOutlined } from '@ant-design/icons';
import { message, Spin } from 'antd';
import VConsole from '../../../node_modules/vconsole/dist/vconsole.min.js'
const Cart: React.FC & {wrappers:string[]} = () => {
  var vConsole = new VConsole();
  let [list, setList] = useState([]);

  let [checkallFlag, setcheckallFlag] = useState(true);
  let [count, setCount] = useState(0)
  let [price, setPrice] = useState(0)
  let [edit, setedit] = useState(false)
  let { getCartData } = useModel('cart', model => ({ getCartData: model.getCartData }))
  let { getCartCount } = useModel('cart', model => ({ getCartCount: model.getCartCount }))

  let { deleteCart } = useModel('cart', model => ({ deleteCart: model.deleteCartData }))
  let { checkCart } = useModel('cart', model => ({ checkCart: model.checkCart }))
  async function getList() {
    let result = await getCartData();
    console.log(result)
    setList(result);//总数据
    let newList: any = []
    result.map((item: any) => {
      let check = { isChecked: true }
      newList.push({ ...item, ...check })
    })
    setList(newList)
    list = newList
    console.log(list)
    //总数量
    let counts = await getCartCount()
    console.log('counts', counts)
    total()
  }
  //全选
  async function checkall() {
    setcheckallFlag(!checkallFlag)
    list.map((item: any) => {
      item.isChecked = !checkallFlag
    })
    total()
  }
  //反选
  async function changeCheck(item: any) {
    // let data = { isChecked: 1, productId: item.product_id }
    // let res=checkCart(data)
    // console.log(res)
    item.isChecked = !item.isChecked
    setcheckallFlag(list.every((item: any) => {
      return item.isChecked
    }))
    total()
  }
  //总价
  function total() {
    let total = list.map((item: any) => item.isChecked ? item.number : 0).reduce((p: number, n: number) => p + n, 0)
    setCount(total)
    let totalPrice = list.map((item: any) => item.isChecked ? item.number * item.market_price : 0).reduce((p: number, n: number) => p + n, 0)
    setPrice(totalPrice)
    // console.log(total, totalPrice)
  }
  //编辑
  function editEvent() {
    setedit(!edit)
  }
  //删除
   function delCart(item: any) {
    console.log(1111)
    list.map((item: any) => {
      if (item.isChecked) {
        let data = { productIds: item.product_id }
         deleteCart(data).then((res:any)=>{
          console.log('删除。。。。。。', res)
          if (res.errno == 1000) {
            message.warning(res.errmsg)
          }
          setList(list)
        });
      }
    })
  }
  // +-
  async function changeCount(item: any, f: string) {
    if (f === '-' && item.number == 0) {
      message.warning('数量为0，不能再减少啦')
      return
    }
    let newlist: any = list.map((item1: any) => {
      if (item.id === item1.id) {
        f === "+" ? item1.number++ : item1.number--
      }
      return item1
    })
    setList(newlist)
    total()
  }
  //下单
  async function order() {
    // Toast.offline('下单功能还未get,耐心等待中。。。', 2);
    message.success('下单功能还未get,耐心等待中。。。')
  }
  //详情
  async function getDetail(id:number){
history.push({pathname:'/cartDetail/detail',query:{id}})
  }
  useEffect(() => {
    getList();

  }, [getCartData])

  return (
    <div className={styles.cart}>
      <header className={styles.header}>
        <span><b>★</b>30天无忧退货</span>
        <span> <b>★</b>48小时快速退货</span>
        <span> <b>★</b>满88免邮费</span>
      </header>
      <div className={styles.list}>
        {
          list.map((item: any) => {
            return <dl key={item.id}>
              <dt onClick={() => { changeCheck(item) }}>
                <b>
                  {

                    item.isChecked ? <CheckCircleOutlined style={{ background: '#BB5353', color: 'white', borderRadius: '50%', border: 'none' }} /> : '⚪'
                  }
                </b>

                <img src={item.list_pic_url} alt="" onClick={()=>{getDetail(item.goods_id)}}/>
              </dt>
              <dd>
                <h3> {item.goods_name} </h3>
                <p>{item.market_price} </p>
              </dd>
              {
                !edit ?
                  <dd>x{item.number}</dd>
                  :
                  <dd>
                    <span onClick={() => { changeCount(item, '-') }}>-</span>
                    <span>{item.number}</span>
                    <span onClick={() => { changeCount(item, '+') }}>+</span>
                  </dd>

              }
            </dl>
          })
        }
      </div>
      {
        !edit ? <footer className={styles.cartfooter}>
          <span>
            <b onClick={checkall} >
              {checkallFlag ? <CheckCircleOutlined style={{ color: '#AB2B2B', borderRadius: '50%', border: 'none', fontSize: '.24rem' }} /> : '⚪'}
            </b>
    已选（{count}）￥{price}</span>
          <span onClick={editEvent}>编辑</span>
          <span onClick={order}>下单</span>
        </footer> :
          <footer className={styles.cartfooter}>
            <span>
              <b onClick={checkall} >
                {checkallFlag ? <CheckCircleOutlined style={{ color: '#AB2B2B', borderRadius: '50%', border: 'none', fontSize: '.24rem' }} /> : '⚪'}
                </b>  已选（{count}）￥{price}
             
            </span>
            <span onClick={editEvent}>完成</span>
            <span onClick={delCart}>删除所选</span>
          </footer>
      }
    </div>
  );
}
// Cart.wrappers=['@/wrappers/auth']
export default Cart